// pages/institufirst/index.js
import urls from '../../utils/urls.js'
import loginFn from '../../utils/login.js'
const http = require('../../utils/util.js')
var app = getApp()
var that
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		schoolId: '',
		showView: false,
		heart: true,
		alldetail: {
			status: 3
		}, //所有的详情
		allClass: [], //所有课程
		imgUrls: [],
		current: 0,
		time: '12:00',
		date: '2018-10-01',
		courseInfo: [],
		courseInfo1: [],
		comments: [],
		commentIndex: 0,
		tabIcon: [{
				id: 0,
				pic: '/img/homes.png',
				piced: '/img/homesd.png',
				title: '主页',
				init: true
			},
			{
				id: 1,
				pic: '/img/course.png',
				piced: '/img/coursed.png',
				title: '课程',
				init: false
			},
			{
				id: 2,
				pic: '/img/tab_teacher.png',
				piced: '/img/tab_teacher_active.png',
				title: '老师',
				init: false
			},
			{
				id: 3,
				pic: '/img/mine.png',
				piced: '/img/mined.png',
				title: '我的',
				init: false
			},
		],
		visitorId: '',
		webUrl: '',
		showauth: true, //显示授权 
		userInfo: '',
		statusNum: '',
		myInfo: '', //个人信息
		studentList: [], //学生列表
		grate: [],
		commentsTotalCount: 0,
		allianceSchools: [], //联盟机构
		allianceCourses: [], //联盟课程
	},

	//切换底部
	seCurrent: function(e) {
		let index = e.currentTarget.dataset.id;
		

		if(!this.data.tabIcon[index]['init']) {
			if(index == 0) {
				this.home_init();
			} else if(index == 1) {
				this.course_init();
			} else if(index == 2) {
				this.teacher_init();
			} else {
				this.my_init();
			}
		}

		let tabIcon = this.data.tabIcon;
		tabIcon[index]['init'] = true;
		this.setData({
			current: index,
			tabIcon: tabIcon
		})
		
		wx.pageScrollTo({
          scrollTop: 0,
          duration: 0
        })
	},
	// 学过的人
	schoollearned: function() {
		let that = this
		let schoollearned = loginFn()
		schoollearned.schoolId = this.data.schoolId;
		wx.request({
			url: urls.schoollearned,
			data: schoollearned,
			success: function(res) {
				let data = res.data.data;
				that.setData({
					learnpeo: res.data.data,
					container: res.data.data.length * 100
				})

			}
		})
	},
	//課程詳情
	gocourseDetail: function(e) {
		let course = e.currentTarget.dataset.id
		wx.navigateTo({
			url: '/pages/classdetail/index?courseId=' + course+'&from=2&schoolId='+this.data.schoolId,

		});

	},

	activeDetail(e) {
		let index = app.getBindParam(e, 'index');
        let active = this.data.activityList[index];

        wx.navigateTo({
            url: '/pages/classdetail/index?courseId='+active.courseId+'&from=2&active_type='+active.active_type
        })
	},
	//老師詳情
	goteacherDetail: function(e) {
		let teachers = e.currentTarget.dataset.id
		wx.navigateTo({
			url: '/pages/teacherdetail/index?teacherId=' + teachers+'&from=2&schoolId='+this.data.schoolId,

		});
	},
	//免费体验
	onChangeShowState: function(e) {
		var that = this
		let index = e.currentTarget.dataset.index
		let courseInfo1 = this.data.courseInfo[index]
		that.setData({
			showView: !that.data.showView,
			courseInfo1: courseInfo1
		})
	},
	// 免费体验预约
	formSubmit: function(e) {
		let that = this
		// var data = e.detail.value
		let formData = loginFn()
		formData.date = this.data.date
		formData.time = this.data.time
		formData.mobile = e.detail.value.mobile
		formData.name = e.detail.value.name
		formData.courseId = that.data.courseInfo1.courseId
		wx.request({
			url: urls.courseApp,
			data: formData,
			success: function(res) {
				wx.showToast({
					title: '提交成功',
					icon: "success",
					duration: 1500,
				})
			}
		})
		that.setData({
			showView: !that.data.showView
		})
		
	},
	// 擦去表单按钮
	delete: function(e) {
		let that = this;
		that.setData({
			showView: !that.data.showView
		})
	},
	// 學過
	haveLearned: function() {
		wx.navigateTo({
			url: '/pages/score/index',
		})

	},
	//  单个机构统计信息
	singleInfo: function() {
		let that = this;
		wx.request({
			url: urls.schoolTotal,
			method: 'GET',
			data: {
				schoolId: that.data.schoolId
			},
			success: function(res) {
				that.setData({
					listword: res.data.data
				})
			}
		})
	},
	// 机构端课程
	classInfo: function() {
		let that = this
		var schoolcourseList = loginFn()
		that.setData({
			schoolId: this.data.schoolId
		})
		schoolcourseList.schoolId = this.data.schoolId
		wx.request({
			url: urls.schoolcourseList,
			method: 'GET',
			data: schoolcourseList,
			success: function(res) {
				that.setData({
					courseInfo: res.data.data.list
				})
			}
		})
	},
	//机构老師
	schoolteacherList: function() {
		let that = this
		app.request({
			url: 'school/teacher',
			data: {
				school_id: that.data.schoolId
			},
			sCallback: (res) => {
				if(res.code == 1) {
					that.setData({
						teacherList: res.data
					})
				}
			}
		})
	},
	// 机构活动
	coursebySchool: function() {
		
		let that = this;
        app.request({
            url: 'school/activity',
            data: {
                school_id: that.data.schoolId
            },
            sCallback: (res) => {
                if(res.code == 1) {
                    that.setData({
                        activityList: res.data
                    })
                }
            }
        });
	},
	//時間選擇
	bindTimeChange: function(e) {
		this.setData({
			time: e.detail.value
		})
	},
	//日期選擇
	bindDateChange: function(e) {
		this.setData({
			date: e.detail.value
		})
	},
	getUserInfo: function(e) {
	},

	checkLogin(){
		var login = setInterval(() => {
			if(wx.getStorageSync('login')){
				clearInterval(login);
				this.init();
			}
		}, 100);
	},

	init(){
		

		
	},
	
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		console.log('options:',options);
		that = this;
		if(options.scene) {
			options.schoolId = decodeURIComponent(options.scene).split('&')[0].split('=')[1]
		}
		var schoolId = options.schoolId;

		var date = new Date();
        var strDate = date.getFullYear()+'-'+(date.getMonth() + 1)+'-'+date.getDate();
		that.setData({
			schoolId: options.schoolId,
			date: strDate,
			
		})

		

		app.visitorEnter({
			title: '机构主页',
			schoolId: this.data.schoolId,
			courseId: '',
			teacherId: '',
			from: 2, //统计来源为老师
		}, (visitorId) => {
			that.setData({
				visitorId: visitorId
			});
		});

		this.home_init();
		var userInfo = wx.getStorageSync('userinfo');
		if (userInfo) {
			this.setData({
				showauth: false,
				userInfo: userInfo
			})
		};
	},

	//所有课程
	getClass: function(loginInfo) {
		that = this
		wx.request({
			url: urls.courseList,
			data: loginInfo,
			success: function(res) {
				if (res.data.code == '0') {
					that.setData({
						allClass: res.data.data
					})
				};
			}
		})
	},
	//所有老师
	getTeacher: function(loginInfo) {
		var that = this;
		wx.request({
			url: urls.teacherList,
			data: loginInfo,
			success: function(res) {
				if (res.data.code == '0') {
					that.setData({
						allTeacher: res.data.data
					})
				};
			}
		})
	},
	//navtab
	scoll_tab: function(e) {
		this.setData({
			status: e.currentTarget.dataset.idx
		})

	},
	//评论列表
	getconmentFn() {
		var that = this;
		app.request({
			url: 'remark/listSchool',
			data: {
				school_id: that.data.schoolId
			},
			sCallback: (res) => {
				if(res.code == 1) {
					that.setData({
						comments: res.data,
						commentsTotalCount: res.data.length
					})
				}
			}
		})
	},

	likeFn: function() { //关注
		var that = this;
		var loginInfo = loginFn();
		loginInfo.schoolId = this.data.alldetail.schoolId;
		wx.request({
			url: urls.focusSchool,
			data: loginInfo,
			success: function(res) {
				if (res.data.code == '0') {
					var likes = !that.data.haslike
					that.setData({
						haslike: likes
					})
				};
			}
		})
	},
	wantFn: function() { //想学
		var that = this;
		var loginInfo = loginFn()
		loginInfo.schoolId = this.data.alldetail.schoolId
		wx.request({
			url: urls.schoolwant,
			data: loginInfo,
			method: 'POST',
			success: function(res) {
				if (res.data.code == '0') {
					wx.showToast({
						title: '想学',
					})
				};
			}
		})
	},

	likeremarkFn: function(e) { //评论点赞
		var that = this;
		var userInfo = wx.getStorageSync('userinfo')
		if (userInfo) {
			var loginInfo = loginFn()
			loginInfo.remarkId = e.currentTarget.dataset.id
			wx.request({
				url: urls.likeSchool,
				method: 'POST',
				data: loginInfo,
				success: function(res) {
					if (res.data.code == '0') {
						that.getconmentFn()
						wx.showToast({
							title: '点赞成功',
						})
					};

				}
			})
		} else {
			this.setData({
				showauth: true
			})
		}

	},


	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {
		// this.checkLogin();
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {
		app.visitorLeave(this.data.visitorId, () => {
			console.log('发送访客离开时间成功');
		});
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {
		app.visitorLeave(this.data.visitorId, () => {
			console.log('发送访客离开时间成功');
		});
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {
		return {
			title: this.data.alldetail.schoolName+'欢迎您！',
			// path: `/pages/index/index?schoolId=${that.data.schoolId}`,
			// imageUrl: "/images/1.jpg",
			success: (res) => {
				console.log("转发成功", res);
			},
			fail: (res) => {
				console.log("转发失败", res);
			}
		}
	},
	//点击评价
	changeCommentIndex(e) {
		that.setData({
			commentIndex: e.currentTarget.dataset.index
		})
	},
	previewFn: function(e) { //预览图片
		wx.previewImage({
			current: e.currentTarget.dataset.url, // 当前显示图片的http链接
			urls: this.data.imgUrls // 需要预览的图片http链接列表
		})
	},
	//去机构管理端
	agentFns: function(res) {
		let that = this
		let statusNum = that.data.statusNum
		// console.log(statusNum, '--dfdfdfdfdfdf')
		//if(statusNum == 4){
		wx.navigateTo({
			url: '/pages/institucharge/institucharge',
		})
		//}   
	},
	//去老师管理端
	agentFn: function(e) {
		wx.navigateTo({
			url: '/pages/teacher-info/index?isAdmin=1',
		})
	},

	getmyInfoFn: function() { //获取个人中心
		var that = this;
		var loginInfo = loginFn()
		wx.request({
			url: urls.userinfo,
			method: 'POST',
			data: loginInfo,
			success: function(res) {
				// console.log(res)
				if (res.data.code == '0') {
					that.setData({
						myInfo: res.data.data
					})
				};
			}
		})
	},
	addStudentFn: function(e) { //添加学生
		wx.navigateTo({
			url: '/pages/addstudent/index',
		})
	},
	addclassFn: function(e) { //
		wx.navigateTo({
			url: '/pages/addclass/index',
		})
	},
	agentFnn: function(e) {
		wx.navigateTo({
			url: '/pages/addinstitution/index',
		})
	},
	getpromotion: function() { //获取优惠券
		wx.navigateTo({
			url: '/pages/coupons/index?getpromotion=true',
		})
	},
	mycardFn: function() { //我的卡券
		wx.navigateTo({
			url: '/pages/coupons/index?mine=true',
		})
	},
	myorderFn: function(e) { //我的订单
		// console.log(e)
		wx.navigateTo({
			url: '/pages/myorder/index?status=' + e.currentTarget.dataset.status,
		})
	},
	loginSuccess: function(e) {
		// console.log('安排')
		// console.log(e)
	},

	testFn: function(e) { //点击开始测试
		var year = 1000 * 60 * 60 * 24 * 365;
		var now = new Date();
		var birth = e.currentTarget.dataset.birthday;
		birth = Date.parse(birth.replace('/-/g', "/"));
		var birthday = new Date(birth);
		var age = parseInt((now - birthday) / year);
		var questionTypeId = 1
		if (age > 6) {
			questionTypeId = 2
		};
		wx.navigateTo({
			url: '/pages/test/index?studentId=' + e.currentTarget.dataset.id + '&questionTypeId=' + questionTypeId,
			success: function(res) {},
			fail: function(res) {},
			complete: function(res) {},
		})
	},
	 //获取学生列表
	getstudentlist: function() {
		var that = this;
		var loginInfo = loginFn()
		wx.request({
			url: urls.studentlist,
			method: 'POST',
			data: loginInfo,
			success: function(res) {
				if (res.data.code == '0') {
					var data = res.data.data;
					for (var i = 0; i < that.data.grate.length; i++) {
						for (var j = 0; j < data.length; j++) {
							if (data[j].gradeId == that.data.grate[i].gradeId) {
								data[j]['grate'] = that.data.grate[i].grade
							};
						}
					}
					// console.log(data)
					that.setData({
						studentList: data
					})
				};
			}
		})
	},
	//获取年级
	getgradeFn: function() { 
		var that = this;
		var loginInfo = loginFn()
		wx.request({
			url: urls.studentGrade,
			method: 'POST',
			data: loginInfo,
			success: function(res) {
				if (res.data.code = '0') {
					that.setData({
						grate: res.data.data.grade
					})
					that.getstudentlist()
				}
			}
		})
	},
	editstudent: function(e) { //编辑学生
		wx.navigateTo({
			url: '/pages/editstudent/index?studentId=' + e.currentTarget.dataset.id + '&idx=' + e.currentTarget.dataset.idx,
		})
	},
	mygoldFn: function(e) { //我的金币
		wx.navigateTo({
			url: '/pages/mygold/index?gold=' + e.currentTarget.dataset.gold
		})
	},
	myscroeFn: function(e) {
		wx.navigateTo({
			url: '/pages/myscore/index?score=' + e.currentTarget.dataset.score
		})
	},
	changeRemark(e){
		this.setData({
			learnpeoIndex: e.currentTarget.dataset.index
		});
	},
	chat: function(){
		wx.navigateTo({
			url: '/pages/message/list/index'
		})
	},
	get_school_detail() {
		
		let that = this;
		app.request({
			url: 'school/detail',
			data:{
				schoolId: that.data.schoolId
			},
			sCallback: (res) => {
				that.setData({
					alldetail: res.data,
					imgUrls: res.data.schoolImages
				})
			}
		})
	},
	//主页初始化
	home_init() {
		console.log();
		//获取学校信息
		this.get_school_detail();
		// //获取学校统计信息
		this.singleInfo();
		// //学校学过的人
		// // this.schoollearned();

		// //活动
		this.coursebySchool();

		// //学校评价
		this.getconmentFn();

		// 联盟机构
		this.get_alliance_school();
	},
	//课程初始化
	course_init() {
		this.classInfo();
		this.get_alliance_course();
	},
	//老师初始化
	teacher_init() {
		this.schoolteacherList();
	},
	//我的初始化
	my_init() {
		this.getmyInfoFn() //获取个人信息
		if (this.data.grate.length > 0) {
			this.getstudentlist()
		} else {
			this.getgradeFn()
		};
	},
	//隐藏预约
	hide(e) {
		console.log(e);
		this.setData({
			showView: false
		})
	},
	//获取联盟机构
	get_alliance_school() {
		let that = this;
		app.request({
			url: 'alliance/school',
			data: {
				school_id: that.data.schoolId
			},
			sCallback: (res) => {
				if(res.code == 1) {
					that.setData({
						allianceSchools: res.data
					})
				}
			}
		})
	},
	//获取联盟课程
	get_alliance_course() {
		let that = this;
		app.request({
			url: 'alliance/course',
			data: {
				school_id: that.data.schoolId
			},
			sCallback: (res) => {
				if(res.code == 1) {
					that.setData({
						allianceCourses: res.data
					})
				}
			}
		})
	},
	//打开地图
    openMap() {
        let data = this.data.alldetail;
        let latitude = parseFloat(data.lat);
        let longitude = parseFloat(data.lng);
        wx.openLocation({
            latitude: latitude, // 必需
            longitude: longitude, // 必需
            name: data.schoolName,
            address: data.addr,
            success: (res) => {

            },
            fail: (res) => {

            },
            complete: (res) => {

            }
        })
    },
})
